<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 资源位ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */

quanli_require('module/base/bill/billRefund.class.php');
quanli_require('module/base/customer/logHandler.class.php');

class ajax_billRefund {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //查询退款单
                    $this->searchBillRefund();
                    break;

                case 2: //编辑退款单信息查询
                    $this->searchRefund();
                    break;

                case 100: //添加、编辑退款单
                    $this->addBillRefund();
                    break;

                case 101://取消退款单
                    $this->cancelBillRefund();
                    break;

                case 102: //审核退款单
                    $this->auditBillRefund();
                    break;

                case 103: //退款单过账
                    $this->postingBillRefund();
                    break;

                case 104: //退款单驳回
                    $this->rejectBillRefund();
                    break;

                case 105: //退款单批量过账
                    $this->batchPosting();
                    break;

                case 106: //退款单打印次数记录
                    $this->print_num();
                    break;

            }

        }

    }

    /**
     * 查询退款单
     */
    private function searchBillRefund (){
        global $G_PGLOB;

        //实例化订单类
        $billRefund = new billRefund( $G_PGLOB->DBCA );

        $bill_info_array = $billRefund->searchBillRefund( $_REQUEST );

        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );


        if ($bill_info_array) {

            foreach($bill_info_array as &$bill) {

                $operate = '';

                if($bill['refund_status'] == 1){

                    if($G_PGLOB->has_permission(1015)){
                        $operate .= '<a href="javascript: void(0);" onclick="bill.audit(\'' . $bill['refund_no'] . '\' , 1);">审核</a>&nbsp;&nbsp;';
                    }
                    if($G_PGLOB->has_permission(1014)){
                        $operate .= '<a href="javascript: void(0);" onclick="bill.add(\'' . $bill['refund_no'] . '\');">修改</a>&nbsp;&nbsp;';
                    }
                    if( $G_PGLOB->has_permission(1016) ){
                        $operate .= '<a href="javascript: void(0);" onclick="bill.cancel(\'' . $bill['refund_no'] . '\');">取消</a>';
                    }
                }

                if($bill['refund_status'] == 2){

                    if($G_PGLOB->has_permission(1017)){
                        $operate .= '<a href="javascript: void(0);" onclick="bill.posting(\'' . $bill['refund_no'] . '\');">过账</a>&nbsp;&nbsp;';
                    }
//                    if( $G_PGLOB->has_permission(1016) ){
//                        $operate .= '<a href="javascript: void(0);" onclick="bill.cancel(\'' . $bill['refund_no'] . '\');">取消</a>';
//                    }
                }

                if($bill['refund_status'] == 4){

                    if($G_PGLOB->has_permission(1018)){
                        $operate .= '<a href="javascript: void(0);" onclick="bill.reject(\'' . $bill['refund_no'] . '\');">驳回</a>';
                    }
                }

                //来源
                if($bill['refund_source'] == 1){
                    $refund_source = "订单退货";
                }elseif ($bill['refund_source'] == 2){
                    $refund_source = "订单取消";
                }else{
                    $refund_source = '其他';
                }

                //状态
                if($bill["refund_status"] == 1){
                    $refund_status = "未审核";
                }elseif ($bill["refund_status"] == 2){
                    $refund_status = "已审核";
                }elseif ($bill["refund_status"] == 3){
                    $refund_status = "已取消";
                }elseif ($bill["refund_status"] == 4){
                    $refund_status = "已过账";
                }else{
                    $refund_status = "未审核";
                }


                $result_array['rows'][] = array(
                    'id' => $bill['bill_no'],
                    'cell' => array(
                        $operate,
                        $refund_status,
                        '<a href="javascript: void(0);" onclick="bill.audit(\''.$bill['refund_no'].'\' , 2);">'.$bill['refund_no'].'</a>',
                        '<a href="javascript: void(0);" onclick="bill.billview(\''.$bill['bill_no'].'\');">'.$bill['bill_code'].'</a>',
                        $bill['custID'],
                        '<a href="javascript: void(0);" onclick="bill.returnview.open(\''.$bill['return_no'].'\' , \''.$bill['refund_source'].'\' );">'.$bill['return_no'].'</a>',
                        $bill['print_num'],
                        $bill['payTypeName'],
                        $bill['refund_account'],
                        $bill['payee'],
                        $bill['refund_amount'],
                        $refund_source,
                        $bill['reason_refund'],
                        $bill['to_city'],
                        $bill['bank_deposit']
                    )
                );
            }
        }

        echo json_encode($result_array);

        return;
    }

    /**
     * 编辑退款单信息查询
     */
    private function searchRefund(){

        global $G_PGLOB;

        if(isset($_REQUEST['refund_no']) && !empty($_REQUEST['refund_no'])){

            //实例化退款类
            $billRefund = new billRefund($G_PGLOB->DBCA);

            $bill_info_array = $billRefund->searchBillRefund( $_REQUEST );

            returnJsonData('ok', 200, $bill_info_array[0]);

        }else{
            returnJsonData('ok', 400);
        }


    }


    /**
     * 添加退款单
     */
    private function addBillRefund(){

        global $G_PGLOB;

        //实例化退款类
        $billRefund = new billRefund($G_PGLOB->DBCA);

        //拆分支付ID和名称
        if(isset($_REQUEST['data']) && !empty($_REQUEST['data'])){
            if(isset($_REQUEST['data']['payType']) && !empty($_REQUEST['data']['payType']) ){
                list($_REQUEST['payTypeID'],$_REQUEST['payTypeName']) = explode('_',$_REQUEST['data']['payType']);
                unset($_REQUEST['data']['payType']);
            }
        }else{
            if(isset($_REQUEST['payType']) && !empty($_REQUEST['payType']) ){
                list($_REQUEST['payTypeID'],$_REQUEST['payTypeName']) = explode('_',$_REQUEST['payType']);
                unset($_REQUEST['payType']);
            }
        }

        //如果有订单号则获取会员ID及名称
        if (isset($_REQUEST['return_bill_code']) && !empty($_REQUEST['return_bill_code'])){

            $result_bill = $G_PGLOB->DBCA->stmt_query('SELECT pcustID,custID,bill_code,bill_no FROM bill_master WHERE bill_code = ?', 's', $_REQUEST['return_bill_code']);
            if (!$result_bill) {
                returnJsonData('订单信息没有找到', 404);
            }

            $_REQUEST['custID'] = $result_bill[0]->custID;
            $_REQUEST['pcustID'] = $result_bill[0]->pcustID;
            $_REQUEST['bill_code'] = $result_bill[0]->bill_code;
            $_REQUEST['bill_no'] = $result_bill[0]->bill_no;

            //查询订单信息
            $sql = "SELECT bill_online_money,bill_received_money FROM bill_master WHERE bill_code = ?";
            $bill_array = $G_PGLOB->DBCA->stmt_query($sql , 's' , $_REQUEST['return_bill_code']);

            $amount_received = $bill_array[0]->bill_received_money;
            if($_REQUEST['refund_no']){
                //查询次订单是否被申请退款过
                $refund_sql="select * from  bill_refund where bill_code=? and refund_status !=3 and refund_no!=?";
                $refund_query = $G_PGLOB->DBCA->stmt_query($refund_sql , 'si' , $_REQUEST['return_bill_code'], $_REQUEST['refund_no']);
            }else{
                //查询次订单是否被申请退款过
                $refund_sql="select * from  bill_refund where bill_code=? and refund_status !=3";
                $refund_query = $G_PGLOB->DBCA->stmt_query($refund_sql , 's' , $_REQUEST['return_bill_code']);
            }

            $refund_money=0;//初始化已申请的退款金额
            foreach($refund_query as  $refund_array){
                $refund_money+=$refund_array->refund_amount;
            }
            //实际可退金额
            $refund_money_1=$amount_received-$refund_money;
            if($refund_money_1 < $_REQUEST['refund_amount']){
                returnJsonData("退款金额不能大于已申请退款金额" , 404);
            }

        }

        if(isset($_REQUEST['data']) && !empty($_REQUEST['data'])){

            $_REQUEST['bill_no'] = $_REQUEST['data']['bill_no'];
            $_REQUEST['refund_source'] = $_REQUEST['data']['refund_source'];
            $_REQUEST['payee'] = $_REQUEST['data']['payee'];
            $_REQUEST['refund_account'] = $_REQUEST['data']['refund_account'];
            $_REQUEST['refund_amount'] = $_REQUEST['data']['refund_amount'];
            $_REQUEST['remark'] = $_REQUEST['data']['remark'];
            $_REQUEST['refund_no'] = $_REQUEST['data']['refund_no'];
        }

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        $result = $billRefund->saveBillRefund($_REQUEST);

        $result['status'] = isset($_REQUEST['refund_status']) ? $_REQUEST['refund_status'] : '';

        echo json_encode($result);

        return;
    }

    /**
     * 审核退款单
     */
    private function auditBillRefund(){

        global $G_PGLOB;

       if(!isset($_REQUEST['refund_no']) || empty($_REQUEST['refund_no'])){
           returnJsonData('参数错误', 400);
       }

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //实例化退款类
        $billRefund = new billRefund($G_PGLOB->DBCA);

        $result = $billRefund->auditBillRefund($_REQUEST);

         returnJsonData($result['message'], $result['code'] );

    }

    /**
     * 退款单过账
     */
private function postingBillRefund(){

    global $G_PGLOB;

    if(!isset($_REQUEST['data']['refund_no']) || empty($_REQUEST['data']['refund_no'])){
        returnJsonData('参数错误', 400);
    }

    $_REQUEST['data']['operator'] = $G_PGLOB->currentUserID;

    //实例化退款类
    $billRefund = new billRefund($G_PGLOB->DBCA);

    $result = $billRefund->postingBillRefund($_REQUEST['data']);

     returnJsonData($result['message'], $result['code'] );
}
    /**
     * 退款单批量过账
     * add by  cdd
     */
    private  function batchPosting(){

        global $G_PGLOB;

        if(!isset($_REQUEST['billNoArr'])){
            returnJsonData('参数错误', 400);
        }

        if(empty($_REQUEST['billNoArr'])){
            returnJsonData('请选择要过账的的数据', 400);
        }


        $billNoArrNum=count($_REQUEST['billNoArr']);//选中的退款单数量
        $bill_str=implode(',',$_REQUEST['billNoArr']);

        //符合过账数据的数量
        $refund_sql="select count(*) as num from  bill_refund where refund_status=? and (refund_no in ($bill_str)) ";
        $refund_num=$G_PGLOB->DBCA->stmt_query($refund_sql,'i',2);
        if($billNoArrNum!=$refund_num[0]->num){
            returnJsonData('存在不可过账数据', 400);
        }

        try{

            //开启事务
            $G_PGLOB->DBCA->beginTransaction();

            //保存退款金额大于已付金额的退单单号
            $refuned_no_str = '';

            foreach ($_REQUEST['billNoArr'] as  $bill_refund_no){
                //日志类
                $logHandler = new logHandler($G_PGLOB->DBCA);

                $bill_refund = new entity('bill_refund');
                $bill_refund->refund_no = $bill_refund_no;
                $G_PGLOB->DBCA->fetch($bill_refund);
                $bill_refund->refund_status = 4;
                $bill_refund->posting_person =$G_PGLOB->currentUserID;
                $bill_refund->posting_time = date('Y-m-d H:i:s');

                $refunded_amount = $bill_refund->refund_amount; //退款金额

                //查询订单信息
                $sql = "SELECT bill_online_money,bill_received_money FROM bill_master WHERE bill_code = ?";
                $bill_array = $G_PGLOB->DBCA->stmt_query($sql , 's' , $bill_refund->bill_code);

                $amount_received = $bill_array[0]->bill_received_money;
                if($_REQUEST['refund_no']){
                    //查询次订单是否被申请退款过
                    $refund_sql="select * from  bill_refund where bill_code=? and refund_status =4 and refund_no!=?";
                    $refund_query = $G_PGLOB->DBCA->stmt_query($refund_sql , 'si' , $bill_refund->bill_code, $bill_refund->refund_no);
                }else{
                    //查询次订单是否被申请退款过
                    $refund_sql="select * from  bill_refund where bill_code=? and refund_status =4";
                    $refund_query = $G_PGLOB->DBCA->stmt_query($refund_sql , 's' , $bill_refund->bill_code);
                }

                $refund_money=0;//初始化已申请的退款金额
                foreach($refund_query as  $refund_array){
                    $refund_money+=$refund_array->refund_amount;
                }
                //实际可退金额
                $refund_money_1=$amount_received-$refund_money;

                if($refund_money_1 < $refunded_amount){

                    $refuned_no_str .= $bill_refund_no . ',';

                }else{

                    //更新退款单主表
                    $G_PGLOB->DBCA->save($bill_refund);

                    $sql_cust='select * from user_master where userID=?';
                    $cust=$G_PGLOB->DBCA->stmt_query($sql_cust,'s',$G_PGLOB->currentUserID);

                    //退款单日志参数
                    $log_array = array(
                        'logCategoryID' => 1,
                        'logItem' => $bill_refund->refund_no,
                        'extend_1' => "退款单过账",
                        'extend_5' => $bill_refund->refund_status,
                        'operator' =>$cust[0]->trueName
                    );
                    $result_log = $logHandler->saveLogInfo($log_array);
                    if($result_log['code'] != 200 ){
                        throw new Exception("链接超时，请重试" , 406);
                    }

                }

            }

            $G_PGLOB->DBCA->commit();

            if( $refuned_no_str != '' ){

                $refuned_str = substr($refuned_no_str,0,strlen($refuned_no_str)-1);
                returnJsonData("单号" . $refuned_str."的退款金额大于已付款金额" , 406);
            }else{

                returnJsonData('批量过账成功', 200);
            }


        }catch (Exception $e){

            $G_PGLOB->DBCA->rollBack();

            if( in_array($e->getCode(),array(404,406))){
                return array('code' => $e->getCode() , 'message' => $e->getMessage());
            }else{
                error_log($e->getMessage());
                return array('code' => 500 , 'message' => '系统错误，过账失败');
            }
        }
    }

    /**
     * 取消退款单
     */
    private function cancelBillRefund (){

        global $G_PGLOB;

        $billRefund = new billRefund($G_PGLOB->DBCA);

        $_REQUEST['data']['operator'] = $G_PGLOB->currentUserID;

        $result = $billRefund->cancleBillRefund($_REQUEST['data']);

        $result['status'] = $_REQUEST['data']['refund_status'];

        echo json_encode($result);

        return;
    }

    /**
     * 退款单驳回
     */
    private function rejectBillRefund(){

        global $G_PGLOB;

        if(!isset($_REQUEST['refund_no']) || empty($_REQUEST['refund_no'])){
            returnJsonData('参数错误', 400);
        }

        $_REQUEST['operator'] = $G_PGLOB->currentUserID;

        //实例化退款类
        $billRefund = new billRefund($G_PGLOB->DBCA);

        $result = $billRefund->rejectBillRefund($_REQUEST);

        returnJsonData($result['message'], $result['code'] );

}
    /*
     * 退款单打印次数修改于记录
     */
    private function print_num(){

        global $G_PGLOB;

        if(!isset($_REQUEST['printBillNoArr']) || empty($_REQUEST['printBillNoArr'])){
            returnJsonData('参数错误', 400);
        }

        foreach($_REQUEST['printBillNoArr'] as $refund_no){
            //日志类
            $logHandler = new logHandler($G_PGLOB->DBCA);
            //获取当前退款单打印次数
            $refund_sql='select print_num from bill_refund where refund_no=?';
            $print_num=$G_PGLOB->DBCA->stmt_query($refund_sql,'i',$refund_no);
            //修改退款单打印次数
            $bill_refund = new entity('bill_refund');
            $bill_refund->refund_no = $refund_no;
            $G_PGLOB->DBCA->fetch($bill_refund);
            $bill_refund->print_num=$print_num[0]->print_num+1;
            $G_PGLOB->DBCA->save($bill_refund);

            $sql_cust='select * from user_master where userID=?';
            $cust=$G_PGLOB->DBCA->stmt_query($sql_cust,'s',$G_PGLOB->currentUserID);

            //退款单日志参数
            $log_array = array(
                'logCategoryID' => 11,
                'logItem' => $bill_refund->refund_no,
                'extend_1' => "退款单打印",
                'extend_5' => $bill_refund->refund_status,
                'operator' => $cust[0]->trueName
            );
            $result_log = $logHandler->saveLogInfo($log_array);

        }
        returnJsonData( 'ok', 200 );

    }

}
